#include "aiswavfile.h"

//默认音频头部数据
WavPcmHeader default_pcmwavhdr =
{
    { 'R', 'I', 'F', 'F' },
    0,
    {'W', 'A', 'V', 'E'},
    {'f', 'm', 't', ' '},
    16,
    1,
    1,
    16000,
    32000,
    2,
    16,
    {'d', 'a', 't', 'a'},
    0
};

AISWavFile::AISWavFile() : curFile(NULL)
{
}

bool AISWavFile::openFile(QString filePath, QFile::OpenMode mode)
{
    pCurPcmWavHdr = new WavPcmHeader;
    memcpy(pCurPcmWavHdr, &default_pcmwavhdr, sizeof(WavPcmHeader));
    curFile = new QFile(filePath);
    if (! curFile->open(mode))
    {
        curFile = NULL;
        return false;
    }
    if (QFile::WriteOnly & mode)
    {
        curFile->write((const char *)pCurPcmWavHdr, sizeof(wave_pcm_hdr));
    }
    return true;
}

bool AISWavFile::writeFile(const char *buffer, qint64 bufferLen)
{
    curFile->write(buffer, bufferLen);
    pCurPcmWavHdr->data_size += bufferLen;
    return curFile->flush();
}

void AISWavFile::closeFile()
{
    pCurPcmWavHdr->size_8 += pCurPcmWavHdr->data_size + 36;
    curFile->seek(4);
    curFile->write((const char *)&(pCurPcmWavHdr->size_8), sizeof(pCurPcmWavHdr->size_8));
    curFile->seek(40);
    curFile->write((const char *)&(pCurPcmWavHdr->data_size), sizeof(pCurPcmWavHdr->data_size));
    curFile->close();
    curFile = NULL;
}
